package cn.org.xuanzp.nty.client;

import cn.org.xuanzp.common.command.Command;
import cn.org.xuanzp.common.command.impl.LoginCommand;
import cn.org.xuanzp.nty.utils.NettyClientUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Classname NettyClient
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/9/26 23:14
 * @Created by xuanzp
 */
public class NettyClient {

    private Map<String, Node> clientMap = new HashMap<String, Node>();
    private Boolean isStart = Boolean.FALSE;


    public void send(String host,Integer port,Command obj){
        Client client = new Client(host,port);
        if(obj instanceof LoginCommand || NettyClientUtil.existCtx(client.getServerId())) {
            NettyClientUtil.send(client.getServerId(),obj);
        }
    }


    public void start() throws Exception {
        doStart();
        isStart = Boolean.TRUE;
    }

    public void addNode(Node node) throws Exception {
        Client client  = new Client(node.getHost(),node.getPort());
        clientMap.put(client.getServerId(),node);
        if(isStart){
            client.start();
        }
    }

    private void doStart() throws Exception {
        Set<String> keys = clientMap.keySet();
        for (String key : keys) {
            Node node = clientMap.get(key);
            Client client = new Client(node.getHost(),node.getPort());
            client.start();
        }
    }

    public static class Node {
        private String host;
        private int port;

        public Node(String host, int port) {
            this.host = host;
            this.port = port;
        }

        public String getHost() {
            return host;
        }

        public void setHost(String host) {
            this.host = host;
        }

        public int getPort() {
            return port;
        }

        public void setPort(int port) {
            this.port = port;
        }
    }
}
